Page({
  data: {
    notifications: [],
    role: '',
  },

  onLoad() {
    this.loadNotifications();
    this.setData({
      role: wx.getStorageSync('role')
    });
  },

  loadNotifications() {
    wx.showLoading({ title: '加载中' });
    wx.request({
      url: 'http://192.168.172.134:5000/api/notificationWx',
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({ notifications: res.data.data });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  viewDetail(e) {
    const id = e.currentTarget.dataset.id;
    const content = e.currentTarget.dataset.content;
    const isLink = /^(https?:\/\/|www\.)/i.test(content.trim());
    if (isLink) {
      wx.navigateTo({
        url: `/pages/out_web/out_web?id=${id}`
      });
    } else {
      wx.navigateTo({
        url: `/pages/notice_detail/notice_detail?id=${id}`
      });
    }
  },

  // createNotice() {
  //   wx.navigateTo({ url: '/pages/notice_editor/notice_editor' });
  // },

  handleDelete(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定删除该通知吗？',
      success: (res) => {
        if (res.confirm) {
          this.deleteNotification(id);
        }
      }
    });
  },
  deleteNotification(id) {
    wx.showLoading({ title: '删除中' });
    wx.request({
      url: `http://192.168.172.134:5000/api/deleteNotice/${id}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          this.loadNotifications();
        } else {
          wx.showToast({ title: '删除失败', icon: 'none' });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  formatDate(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  }
});